package dsk.demo.product;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

public class test {

    private volatile static Object obj;

    public Object getInstance() {
        if (obj == null) {
            synchronized (this) {
                if (obj == null) {
                    obj = new Object();
                }
            }
        }
        return obj;
    }

    /**
     * 加密
     */
    public static String encode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c <= 'Z' && c >= 'A') {
                String addStr;
                if (c == 'Z')
                    addStr = "A";
                else
                    addStr = (char) (c + 1) + "";
                result = result + addStr.toLowerCase();
            } else if (c <= 'z' && c >= 'a') {
                String addStr;
                if (c == 'z')
                    addStr = "a";
                else
                    addStr = (char) (c + 1) + "";
                result = result + addStr.toUpperCase();
            } else {
                String addStr;
                if (c == '9')
                    addStr = "0";
                else
                    addStr = (char) (c + 1) + "";
                result = result + addStr;
            }
        }
        return result;
    }

    /**
     * 解密
     */
    public static String decode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c <= 'Z' && c >= 'A') {
                String addStr;
                if (c == 'A')
                    addStr = "Z";
                else
                    addStr = (char) (c - 1) + "";
                result = result + addStr.toLowerCase();
            } else if (c <= 'z' && c >= 'a') {
                String addStr;
                if (c == 'a')
                    addStr = "z";
                else
                    addStr = (char) (c - 1) + "";
                result = result + addStr.toUpperCase();
            } else {
                String addStr;
                if (c == '0')
                    addStr = "9";
                else
                    addStr = (char) (c - 1) + "";
                result = result + addStr;
            }
        }
        return result;
    }


    /**
     * @param hexString
     * @return
     */
    public static String change(String hexString) {
        // linkedHashMap 遍历
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
        //字符串比较大小
        hexString.compareTo(hexString);
        // 字符串正则判断
        if (!hexString.matches("[0-9,a-f,A-F]")) {
            return hexString;
        }
        // 16进制转十进制整数  AF  这种格式的.
        int i = Integer.parseInt(hexString, 16);
        // 16进制转十进制 0xAA 这种格式的
        Integer.decode(hexString);
        // 十进制转2进制
        String binaryString = Integer.toBinaryString(i);
        while (binaryString.length() < 4) {
            binaryString = "0" + binaryString;
        }
        //字符串反转         回文串长度差小判断到大,大的可以由小的状态转移, 长度差从小到大
        String binaryStringReverse = new StringBuilder(binaryString).reverse().toString();
        // 双指针 滑动窗口 哈希表记录个数重复就-2. 判断是否符合要求
        //二进制字符串转十六进制
        return Long.toHexString(Long.parseLong(binaryStringReverse, 2)).toUpperCase();
    }

    @Test
    public void fun321() throws UnsupportedEncodingException {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int threadNumber = 10;
        // 设置核心线程数
        executor.setCorePoolSize(threadNumber);
        // 设置线程队列大小
        executor.setQueueCapacity(threadNumber * 20);
        // 设置线程最大线程数量
        executor.setMaxPoolSize(threadNumber * 2);
        // 设置最大线程空闲时间,达到最大空闲时间则自动销毁
        executor.setKeepAliveSeconds(60);
        // 设置线程池名称前缀
        executor.setThreadNamePrefix("MyExecutor");

        /*
         * rejection-policy：当pool已经达到max size的时候，如何处理新任务
         * CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 初始化
        executor.initialize();

        ExcelReader reader = ExcelUtil.getReader(new File("C:\\Users\\戴世坤\\Desktop\\无标题1.xlsx"));
        List<Map<String, Object>> images = reader.readAll();
        String filePath = "D:\\Vietti\\vietti3";
        File file = new File(filePath);
        if (file.exists()) {
            file.mkdirs();
        }
        List<String> fileNames = Arrays.asList(file.list());
        CountDownLatch countDownLatch = new CountDownLatch(images.size());
        for (Map<String, Object> image : images) {
            String product_img = (String) image.get("photo");
            String[] split = product_img.split("/");
            if (fileNames.contains(split[split.length - 1])) {
                countDownLatch.countDown();
                continue;
            }
            executor.execute(() -> {
                try {
                    getAndDownloadImage(product_img, filePath, split[split.length - 1]);
                } catch (Exception e) {
                    System.out.println("图片下载失败: " + product_img);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            countDownLatch.await();
        } catch (Exception e) {

        }
    }

    @Test
    public void fun34() {
        ExcelReader reader = ExcelUtil.getReader(new File("C:\\Users\\戴世坤\\Desktop\\vietti图片.xlsx"));
        List<Map<String, Object>> images = reader.readAll();
        for (List<Map<String, Object>> imageSp : CollectionUtil.split(images, 500)) {
            for (Map<String, Object> image : imageSp) {
                String product_img = (String) image.get("photo");
                String[] split = product_img.split("/");
                String finalUrl = "https://res.famkools.net/supplier/vietti/" + split[split.length - 1];
                System.out.println("update t_supplier_product_dresscode set photo = \"" + finalUrl + "\" where photo = \"" + product_img + "\";");
            }
        }
    }

    public String getAndDownloadImage(String url, String filePath, String fileName) throws IOException {
        HttpResponse response = HttpUtil.createGet(url)
                .timeout(1000 * 60 * 10)
                .execute();
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(filePath + File.separator + fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(response.bodyBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
        response.close();
        System.out.println("图片下载成功: " + url);
        return file.getName();
    }

    @Test
    public void fun36() {
        List<String> list = new ArrayList<>();
        list.add("111");
        List<String> sub = CollectionUtil.sub(list, 0, 1);
        System.out.println(JSONUtil.toJsonStr(sub));
    }

}
